//
//  ZCAbnormalAllViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/24.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAbnormalAllViewController.h"
#import "ZCAbnormalSignListTableViewCell.h"
#import "ZCAbnormalModel.h"
#import "ZCAbnormalScanPhotoViewController.h"


static NSString *signListCellID = @"ZCAbnormalSignListTableViewCell";

@interface ZCAbnormalAllViewController ()<UITableViewDelegate, UITableViewDataSource, ZCAbnormalSignListTableViewCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ZCAbnormalAllViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCAbnormalSignListTableViewCell class] forCellReuseIdentifier:signListCellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.mj_footer.automaticallyHidden = YES;
    }
    return _tableView;
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.title = @"全部异常";
    [self.view addSubview:self.tableView];
    self.page = 1;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)backToHome {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)loadData {
    self.page = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.orderNo.length > 0 ? self.orderNo : @(0) forKey:@"orderNo"];
    [param setObject:self.vin forKey:@"vin"];
    [param setObject:@(self.page) forKey:@"pageNo"];
    [param setObject:@(10) forKey:@"pageSize"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:AllException params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (![responseObject[@"message"] isEqualToString:@"success"]) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }else {
                [weakSelf.hud hideAnimated:YES];
                NSMutableArray *tempA = [NSMutableArray array];
                ZCAbnormalAllModel *signModel = [ZCAbnormalAllModel yy_modelWithDictionary:responseObject[@"data"]];
                [tempA addObjectsFromArray:signModel.records];
                weakSelf.dataArray = [tempA copy];
                [weakSelf.tableView reloadData];
            }
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer resetNoMoreData];
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

- (void)loadMoreData {
    self.page++;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.orderNo forKey:@"orderNo"];
    [param setObject:self.vin forKey:@"vin"];
    [param setObject:@(self.page) forKey:@"pageNo"];
    [param setObject:@(10) forKey:@"pageSize"];
    
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:AllException params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (![responseObject[@"message"] isEqualToString:@"success"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }else {
                NSMutableArray *tempA = [weakSelf.dataArray mutableCopy];
                ZCAbnormalAllModel *signModel = [ZCAbnormalAllModel yy_modelWithDictionary:responseObject[@"data"]];
                [tempA addObjectsFromArray:signModel.records];
                weakSelf.dataArray = [tempA copy];
                [weakSelf.tableView reloadData];
                if (signModel.records.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_footer endRefreshing];
            weakSelf.page--;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCAbnormalSignListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:signListCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.isDelete = NO;
    cell.indexPath = indexPath;
    ZCAbnormalSignModel *signModel = (ZCAbnormalSignModel *)self.dataArray[indexPath.section];
    cell.name = [NSString stringWithFormat:@"%@ - %@",signModel.level2Name,signModel.level3Name];
    cell.imageArray = [signModel.exceptionDetails mutableCopy];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(140);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - ZCAbnormalSignListTableViewCellDelegate
- (void)abnormalSignListTableViewCellDeleteButtonClickWithIndex:(NSIndexPath *)index {
    //点击删除按钮删除本条数据
    //数据
    ZCAbnormalSignModel *signM = (ZCAbnormalSignModel *)self.dataArray[index.row];
    NSMutableArray *signA = [self.dataArray mutableCopy];
    [signA removeObject:signM];
    self.dataArray = [signA copy];
    
    //界面
    [self.tableView reloadData];
    
    if ([self.delegate respondsToSelector:@selector(abnormalSignListViewLongPressImageWithSignArray:)]) {
        [self.delegate abnormalSignListViewLongPressImageWithSignArray:self.dataArray];
    }
}

- (void)abnormalSignListTableViewCellScanPhotoWithCellIndex:(NSIndexPath *)cellIndex itemIndex:(NSIndexPath *)itemIndex {
    ZCAbnormalSignModel *signM = (ZCAbnormalSignModel *)self.dataArray[cellIndex.section];
    
    ZCAbnormalScanPhotoViewController *scanVC = [[ZCAbnormalScanPhotoViewController alloc] init];
    scanVC.dataArray = signM.exceptionDetails;
    scanVC.nowIndex = itemIndex;
    [self.navigationController pushViewController:scanVC animated:YES];

}

- (void)abnormalSignListTableViewCellLongPressImageWithCellIndex:(NSIndexPath *)cellIndex itemIndex:(NSIndexPath *)itemIndex {
    ZCAbnormalSignModel *signM = (ZCAbnormalSignModel *)self.dataArray[cellIndex.row];
    ZCAbnormalListDetailModel *detailM = (ZCAbnormalListDetailModel *)signM.exceptionDetails[itemIndex.item];
    NSMutableArray *tempA = [signM.exceptionDetails mutableCopy];
    [tempA removeObject:detailM];
    signM.exceptionDetails = [tempA copy];
    if (signM.exceptionDetails.count == 0) {
        NSMutableArray *signA = [self.dataArray mutableCopy];
        [signA removeObject:signM];
        self.dataArray = [signA copy];
    }
    [self.tableView reloadData];

}


@end
